package com.chaucer.demo.transmit;

import com.chaucer.demo.enums.BusinessSourceEnum;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description TODO
 * @Author Chaucer
 * @Date 2021/9/2 22:34
 */
public class ReceiveHandlerFilter implements Filter {

    private static Logger logger = LoggerFactory.getLogger(ReceiveHandlerFilter.class);

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        // 获取业务来源
        printHeaders(request);
        // 设置业务来源
        setBusinessSource(request);
        // 打印最终的业务来源

        HttpServletRequest servletRequest = (HttpServletRequest) request;
        logger.info("request url:{},businessSource: {}", servletRequest.getRequestURL(), BusinessSourceThreadLocal.get());
        filterChain.doFilter(request, response);

        BusinessSourceThreadLocal.clearThreadLocal();

    }


    private void setBusinessSource(ServletRequest request) {
        // 设置默认业务来源
        String businessSource = ((HttpServletRequest) request).getHeader(IsolateConstants.businessSourceKey);
        if (businessSource != null && !businessSource.isEmpty()) {
            //设置业务来源到当前线程
            BusinessSourceThreadLocal.set(businessSource);
            return;
        }
        String serverName = request.getServerName();
        if (StringUtils.isNotEmpty(serverName)) {
            for (BusinessSourceEnum sourceEnum : BusinessSourceEnum.values()) {
                if (serverName.startsWith(sourceEnum.getCode())) {
                    // 域名匹配开头匹配
                    BusinessSourceThreadLocal.set(sourceEnum.getCode());
                    return;
                }
            }
        }
        // 根据origin判断
        String origin = ((HttpServletRequest) request).getHeader("Origin");
        if (StringUtils.isNotEmpty(origin)) {
            for (BusinessSourceEnum sourceEnum : BusinessSourceEnum.values()) {
                if (origin.startsWith("http://" + sourceEnum.getCode())) {
                    // 域名匹配开头匹配
                    BusinessSourceThreadLocal.set(sourceEnum.getCode());
                    return;
                }
            }
        }
        // 根据X-Forwarded-Host判断
        String xForwardedHost = ((HttpServletRequest) request).getHeader("X-Forwarded-Host");
        if (StringUtils.isNotEmpty(xForwardedHost)) {
            for (BusinessSourceEnum sourceEnum : BusinessSourceEnum.values()) {
                if (xForwardedHost.startsWith(sourceEnum.getCode())) {
                    // 域名匹配开头匹配
                    BusinessSourceThreadLocal.set(sourceEnum.getCode());
                    return;
                }
            }
        }
//        }
    }

    private void printHeaders(ServletRequest request) {
        //2.获得所有头的名称
        Map<String, Object> headers = new HashMap<>();
        Enumeration<String> headerNames = ((HttpServletRequest) request).getHeaderNames();
        while (headerNames.hasMoreElements()) {//判断是否还有下一个元素
            String key = headerNames.nextElement();//获取headerNames集合中的请求头
            String value = ((HttpServletRequest) request).getHeader(key);//通过请求头得到请求内容
            headers.put(key, value);
        }
        if (logger.isDebugEnabled()) {
            logger.debug("headers: {}", headers);
        }
    }

    @Override
    public void destroy() {
        BusinessSourceThreadLocal.clearThreadLocal();
    }
}